package com.algorhythms.infinity;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.TextView;
import android.widget.Toast;

/**
 * TEST ONLY - NOT PRODUCTION CODE
 */
public class CategoryViewActivity extends ListActivity {
    private static final int ACTIVITY_CREATE=0;

    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;

    public static final String categoryIdKey = "catIdKey";

    private CategoryDbAdapter mDbHelper;
    private Long mTripId;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("Activity creating.");
        setContentView(R.layout.category_view_layout);

        // Check the saved state for the trip id
        mTripId = (savedInstanceState == null) ? null :
                (Long) savedInstanceState.getSerializable(TripsDbAdapter.KEY_ROWID);
        // Check the extras for the trip id
        if (mTripId == null) {
            Bundle extras = getIntent().getExtras();
            mTripId = extras != null ? extras.getLong(TripsDbAdapter.KEY_ROWID)
                    : null;
        }
        // If at this point there is no trip id, glitch has occured, finish this activity
        if(mTripId == null)
            finish();

        // Get the trips adapter and use it to access the title of this trip
        TripsDbAdapter tripsAdapter = TripsDbAdapter.getInstance(this);
        tripsAdapter.open();

        Cursor item = tripsAdapter.fetchTrip(mTripId);
        startManagingCursor(item);
        TextView title = (TextView)findViewById(R.id.categoryHeader);
        title.setText("Categories for " + item.getString(item.getColumnIndexOrThrow(TripsDbAdapter.KEY_TRIPNAME)));

        //tripsAdapter.close();

        mDbHelper = CategoryDbAdapter.getInstance(this);
        mDbHelper.open();
        System.out.println("Database open.");
        fillData(mTripId);
        registerForContextMenu(getListView());
    }

    private void fillData(long tripId) {
        Cursor catCursor = mDbHelper.fetchAllCategories(tripId);
        startManagingCursor(catCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{CategoryDbAdapter.KEY_CATNAME};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.text1};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter notes =
                new SimpleCursorAdapter(this, R.layout.list_row, catCursor, from, to);
        setListAdapter(notes);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID, 0, R.string.menu_add);
        return true;
    }

    /*@Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case INSERT_ID:
                System.out.println("Menu item selected: creating category");
                createCategory();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }*/

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, R.string.menu_delete);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case DELETE_ID:
                AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
                mDbHelper.deleteCategory(info.id);
                fillData(mTripId);
                return true;
        }
        return super.onContextItemSelected(item);
    }

    /*private void createCategory() {
        System.out.println("Attempting to create a category...");
        promptAndAddCategory();
    }*/

    public void createCategory(View view) {
        System.out.println("Attempting to create a category...");
        promptAndAddCategory();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, ItemViewActivity.class);
        i.putExtra(categoryIdKey, id);
        startActivityForResult(i, ACTIVITY_CREATE);
    }

    private void promptAndAddCategory() {
        System.out.println("Add category started. Building the alert");
        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle("Add Category");
        alert.setMessage("What's the name of this category?");

        // Set an EditText view to get user input
        final EditText input = new EditText(this);
        alert.setView(input);
        final Context c = this;

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                char[] charseq = new char[input.getText().length()];
                input.getText().getChars(0, input.getText().length(), charseq, 0);
                String catName = new String(charseq);

                if(!"".equals(catName.trim())) {
                    System.out.println("Creating a new category.");
                    mDbHelper.createCategory(catName, mTripId);
                    fillData(mTripId);
                }
            }
        });

        alert.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Canceled.
                    }
                });

        alert.show();
    }
}